/*
 * INode.cpp
 *
 *  Created on: Jul 7, 2009
 *      Author: elkobir
 */

#include "INode.h"


INode::INode(unsigned char* data) {

	this->_fileType = data[0];
	this->_hardLinksNum = data[1];
	this->_fileSize = Utils::GetInt(data,2);
	for(unsigned int i = 0; i<10; i++){
		int val = Utils::GetInt(data,6 + (i*4));
		this->_direct.push_back(val);
	}
	this->_indirect = Utils::GetInt(data,46);
}

INode::INode() {

	this->_fileType = 0;
	this->_hardLinksNum = 0;
	this->_fileSize = 0;
	for(unsigned int i = 0; i<10; i++){
		int val = 0;
		this->_direct.push_back(val);
	}
	this->_indirect = 0;
}

INode::~INode() {
	// TODO Auto-generated destructor stub
}

unsigned char* INode::toBytes(){
	unsigned char* res = Utils::InitBytes(50);
	//TODO who ever control res control his release memory

	res[0] = (unsigned char)this->_fileType;
	res[1] = (unsigned char)this->_hardLinksNum;
	Utils::IntToByte(this->_fileSize,res,2);
	for(unsigned int i = 0; i<10; i++){
		int val = this->_direct.at(i);
		Utils::IntToByte(val,res,6 + (i*4));
	}
	Utils::IntToByte(this->_indirect,res,46);

	return res;
}

int INode::getType(){
	return this->_fileType;
}

void INode::setType(int type){
	this->_fileType = type;
}

int INode::getHardLinksNum(){
	return this->_hardLinksNum;
}

int INode::incHardLinksNum(){
	this->_hardLinksNum++;
	return _hardLinksNum;
}

int INode::decHardLinksNum(){
	this->_hardLinksNum--;
	return _hardLinksNum;
}

void INode::setHardLinksNum(int num){
	this->_hardLinksNum = num;
}

int INode::getFileSize(){
	return this->_fileSize;
}

void INode::setFileSize(int fileSize){
	this->_fileSize = fileSize;
}

int INode::getDataBlockAt(int index){
	int result = 0;
	if (index < 10){
		result = _direct.at(index);
	}

	return result; // 0 if indirect
}

void INode::setDataBlockAt(int index, int dblockNum){
	if (index < 10){
		_direct[index] = dblockNum;
	}
}

vector<int>* INode::getBlockList(int blockSize , unsigned char* indirectBytes){
	vector<int>* result;

	if (_indirect != 0){
		INodeIndirect* iNodeIndirect = new INodeIndirect(blockSize, indirectBytes);
		result = iNodeIndirect->getBlockList();
	} else {
		result = new vector<int>();
	}

	for (int i = 0; i < 10; i++){
		int val = _direct.at(i);
		if (val != 0){
			result->push_back(val);
		}
	}

	return result;
}


